<?php
	include_once "db/db.php";
	
	/**
		Process a cash transaction (taking out a loan as necessary, and giving money to appropriate players)
		@param string $player Player ID
		@param string $amount Cash amount (positive or negative)
		@param string $event Description of the transaction taking place
		@param string $tocareer The career which earns the money for this transaction
	*/
	function process_transaction($player, $amount, $event="", $tocareer="", $autoLoan=true) {
		// Variable setup
		global $current_game, $current_game_id;
		$game = $current_game_id;
		
		// Process transaction...
		// Parse money
		$amount = 0 + str_replace(array("$",","), "", $amount);
		
		// Find the destination player (if someone with selected career)
		$toplayer = mysql_fetch_assoc(mysql_query("
				SELECT `player` AS `id` FROM `gameplayer` 
				WHERE `game` = '$game' AND `career` = '" . $tocareer . "'"));
		
		// Check if we're in debt. If so, borrow money.
		if ($autoLoan) {
			$settings = get_settings();
			$cashEarned = mysql_result(mysql_query("
				SELECT SUM(`amount`) FROM `cash` 
				WHERE `game` = '$game' AND `player` = '$player'"), 0);
			$newCashTotal = 0 + $settings['initialcash'] + $cashEarned + $amount;
			if ($newCashTotal < 0) {
				$loan_amount = $settings['loansize'] * ceil(((float)-$newCashTotal) / $settings['loansize']);
				mysql_query("
					INSERT INTO `cash` (`datetime`, `game`, `player`, `amount`, `event`)
					VALUES ('" . current_date_time() . "', '$game', 
							'$player', '$loan_amount', 'LOAN: $event')");
			}
		}
		
		// Save the transaction
		mysql_query("
			INSERT INTO `cash` (`datetime`, `game`, `player`, `amount`, `event`, `tocareer`, `toplayer`) 
			VALUES ('" . current_date_time() . "', 
				'$game', '$player', 
				'" . $amount . "',
				'" . $event . "',
				" . ($tocareer=="" ? "NULL" : "'" . $tocareer . "'") . ",
				" . ($toplayer['id'] == "" ? "NULL" : "'" . $toplayer['id'] . "'") . ")");
		
		// Give the money to the destination player
		if ($toplayer['id'] != "") {
			mysql_query("
				INSERT INTO `cash` (`datetime`, `game`, `player`, `amount`, `event`, `tocareer`, `toplayer`)
				VALUES ('" . current_date_time() . "', '$game', '" . $toplayer['id'] . "',
					'" . -($amount) . "', 'TRANSFER: " . $event . "', 
					'" . $tocareer . "', '$player')");
		}
	}
	
	/* 
		Change turn
		NOTE: we use this method to check if the game hasn't started yet (ie it's noone's turn).
			  If we havenn't started yet then we need to first apply people's debts
	 */
	if (isset($_POST['prevTurn']) || isset($_POST['nextTurn'])) {
		// List players, saving the index of the player who's turn it is
		$players_query = mysql_query("
			SELECT `player`.`id`, `gameplayer`.`university` AS `university`
			FROM `gameplayer` LEFT JOIN `player` ON (`gameplayer`.`player` = `player`.`id`)
			WHERE `gameplayer`.`game` = '$current_game_id'
			ORDER BY `player`.`name`");
		$players = array();
		$player_turn_index = -1;
		$index = 0;
		while ($player = mysql_fetch_assoc($players_query)) {
			array_push($players, $player);
			if ($current_game['turn'] == $player['id']) {
				$player_turn_index = $index;
			}
			++$index;
		}
		
		// If this is the first turn of the game, record uni fees
		$settings = get_settings();
		if ($current_game['turn'] == "") {
			foreach ($players as $player) {
				if ($player['university'] == "1") {
					process_transaction($player['id'], -$settings['unifees'], "UNI FEES");
				}
			}
		}
		
		// Set the new player id accordingly
		if ($player_turn_index == -1) {
			// First turn
			$new_turn_index = 0;
		} else if (isset($_POST['prevTurn'])) {
			// Previous turn
			if ($player_turn_index == 0) {
				$new_turn_index = count($players)-1;
			} else {
				$new_turn_index = $player_turn_index-1;
			}
		} else {
			// Next turn
			if ($player_turn_index == count($players)-1) {
				$new_turn_index = 0;
			} else {
				$new_turn_index = $player_turn_index+1;
			}
		}
		// Update
		mysql_query("UPDATE `game` SET `turn` = '" . $players[$new_turn_index]['id'] . "' WHERE `id` = '$current_game_id' LIMIT 1");
	}
	
	/* Money (transaction) */
	elseif (isset($_POST['moneySubmit'])) {
		$amount = $_POST['amount'];
		$event = $_POST['event'];
		$tocareer = $_POST['tocareer'];
		
		global $current_game;
		$player_array = mysql_fetch_assoc(mysql_query("
				SELECT `income`.`income`, `income`.`tax`
				FROM `gameplayer` LEFT JOIN `income` ON (`gameplayer`.`income` = `income`.`id`)
				WHERE `gameplayer`.`player` = '" . $current_game['turn'] . "'
				LIMIT 1"));
		
		if ($_POST['moneyAction'] == "payday") {
			$amount = $player_array['income'];
			$event = "Pay day";
			$tocareer = "";
		} elseif ($_POST['moneyAction'] == "taxes") {
			$amount = -$player_array['tax'];
			$event = "Taxes due";
			$tocareer = "";
		} elseif ($_POST['moneyAction'] == "earn") {
			$tocareer = "";
		} elseif ($_POST['moneyAction'] == "pay") {
		}
		
		process_transaction($current_game['turn'], $amount, $event, $tocareer);
	}
	
	/* Cards */
	elseif (isset($_POST['cardSubmit'])) {
		$gameplayerwhere = "`game` = '$current_game_id' AND `player` = '" . $current_game['turn'] . "'";
		$newValueLiteral = "'" . $_POST['id'] . "'";
		if ($_POST['type'] == "career") {
			mysql_query("UPDATE `gameplayer` SET `career` = $newValueLiteral WHERE $gameplayerwhere LIMIT 1");
		} elseif ($_POST['type'] == "salary") {
			mysql_query("UPDATE `gameplayer` SET `income` = $newValueLiteral WHERE $gameplayerwhere LIMIT 1");
		} elseif ($_POST['type'] == "house") {
			mysql_query("UPDATE `gameplayer` SET `house` = $newValueLiteral WHERE $gameplayerwhere LIMIT 1");
		} elseif ($_POST['type'] == "life") {
			// Check if we're stealing from another player
			if (isset($_POST['stealFrom'])) {
				mysql_query("
						DELETE FROM `playerlifecard` 
						WHERE `game` = '$current_game_id' AND 
							`player` = '" . $_POST['stealFrom'] . "' AND
							`lifecard` = $newValueLiteral
						LIMIT 1");
			}
			// Save new lifecard to current player
			mysql_query("
					INSERT INTO `playerlifecard` (`game`, `player`, `lifecard`, `datetime`)
					VALUES ('$current_game_id', '" . $current_game['turn'] . "', 
						$newValueLiteral, '" . current_date_time() . "')");
		}
	}
	
	/* Family */
	elseif (isset($_POST['familySubmit'])) {
		if ($_POST['type'] == "marry") {
			mysql_query("
				UPDATE `gameplayer` SET `married` = '1' 
				WHERE `game` = '$current_game_id' AND `player` = '" . $current_game['turn'] . "' 
				LIMIT 1");
		} else {
			mysql_query("
				INSERT INTO `playerfamily` (`game`, `player`, `gender`, `datetime`) 
				VALUES ('$current_game_id', '" . $current_game['turn'] . "', 
					'" . ($_POST['type']=="girl"?"1":"0") . "', '" . current_date_time() . "')");
		}
	}
	
	/* Retirement */
	elseif (isset($_POST['retireSubmit'])) {
		if ($_POST['retirementHome'] != "") {
			mysql_query("
				UPDATE `gameplayer` SET `retired` = '" . $_POST['retirementHome'] . "' 
				WHERE `game` = '$current_game_id' AND `player` = '" . $current_game['turn'] . "' 
				LIMIT 1");
		}
	}
	
	/* Finish Game (only possible when everyone's retired) */
	elseif (isset($_POST['endGameSubmit'])) {
		// Make sure this is run only once
		if (mysql_result(mysql_query("SELECT `turn` FROM `game` WHERE `id` = '$current_game_id' LIMIT 1"), 0) != "") {
	
			// Pay off debts
			$settings = get_settings();
			$players_query = mysql_query("
					SELECT `gameplayer`.`player` AS `id`, SUM(`cash`.`amount`) AS `debts` 
					FROM `gameplayer` LEFT JOIN `cash` ON (`gameplayer`.`player` = `cash`.`player` AND `gameplayer`.`game` = `cash`.`game`)
					WHERE `gameplayer`.`game` = '$current_game_id' AND `cash`.`event` LIKE 'LOAN%'
					GROUP BY `gameplayer`.`player`");
			while ($player = mysql_fetch_assoc($players_query)) {
				process_transaction($player['id'], 
						-1.0*$player['debts']/$settings['loansize']*$settings['loanpayback'],
						"REPAY ALL LOANS", "", false);
			}
		
			// Give retirement life cards to player in Millionaire Estate with most cash
			$richest_player = mysql_fetch_assoc(mysql_query("
				SELECT `gameplayer`.`player` AS `id`, SUM(`cash`.`amount`) AS `cashInHand`
				FROM `gameplayer`
					LEFT JOIN `cash` ON (`gameplayer`.`game` = `cash`.`game` AND `gameplayer`.`player` = `cash`.`player`)
					LEFT JOIN `retirementhome` ON (`gameplayer`.`retired` = `retirementhome`.`id`)
				WHERE `gameplayer`.`game` = '$current_game_id' AND `retirementhome`.`lifecardssafe` = '0'
				GROUP BY `gameplayer`.`player`
				ORDER BY `cashInHand` DESC
				LIMIT 1"));
			if ($richest_player['id'] != "") {
				$lifecard_ids = get_millionaire_lifecards($current_game_id);
				foreach ($lifecard_ids as $lifecard_id) {
					mysql_query("
						INSERT INTO `playerlifecard` (`game`, `player`, `lifecard`, `datetime`) 
						VALUES ('$current_game_id', '" . $richest_player['id'] . "', 
								'$lifecard_id', '" . current_date_time() . "')");
				}
			}
			
			// Set turn to NULL
			mysql_query("UPDATE `game` SET `turn` = NULL WHERE `id` = '$current_game_id' LIMIT 1");
		}
		
		header("location:play.php?finished=true");
		exit();
	}
	
	
	// Navigate (also strip post data)
	header("location:play.php");
?>
